'use strict';
import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    ScrollView,
    ToastAndroid,
} from 'react-native';
import StorageUtil from '../util/StorageUtil';
import TouchButton from "../widget/btn/HighlightButton";

const STORAGE_KEY_ONE = 'AsyncStorageDemo';

/** react-native-storage */
export default class AsyncStorageDemo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            messages: [],
        };
        this.textInfo = '';
    };

    render() {
        return (
            <ScrollView>
                <View style={styles.container}>
                    <TextInput
                        style={{height: 40, width: 200}}
                        placeholder="输入!"
                        onChangeText={(inputText) => {
                            this.textInfo = inputText;
                        }}
                    />

                    <View style={{height: 15}}/>
                    <TouchButton disabled={false} title={'存储数据'} onPress={() => this._doSave()}/>

                    <View style={{height: 15}}/>
                    <TouchButton disabled={false} title={'删除数据'} onPress={() => this._doRemove()}/>

                    <View style={{height: 15}}/>
                    <TouchButton disabled={false} title={'查询数据'} onPress={() => this._doLoad()}/>

                    {/* 在render里面执行一些函数：用{}括起来 */}
                    {this.state.messages.map((m) => <Text style={styles.content} key={m}>{m}</Text>).reverse()}
                </View>
            </ScrollView>
        );
    };

    _doSave() {
        let value = this.textInfo;
        StorageUtil.getInstance().doSave(STORAGE_KEY_ONE, value);
        this._appendMessage('已存储' + STORAGE_KEY_ONE + ':' + value);
    }

    _doRemove() {
        StorageUtil.getInstance().doRemoveByKey(STORAGE_KEY_ONE);
        this._appendMessage('已删除' + STORAGE_KEY_ONE);
    }

    _doLoad() {
        StorageUtil.getInstance().doLoad(STORAGE_KEY_ONE, null, null, (ret) => {
            ToastAndroid.show(ret, ToastAndroid.SHORT);
        });
    }

    _appendMessage(message) {
        // 要更新界面就要setState
        this.setState({messages: this.state.messages.concat(message)});
    }
}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'column',
        alignItems: 'center',
        // justifyContent: 'center',
    },
    content: {
        fontSize: 13,
        textAlign: 'left',
        margin: 10,
    },
});
